

$(function () {
    layui.use(['jquery', 'form', 'layer', 'table', 'laytpl', 'laydate', 'element', 'util'], function() {
        var $ = layui.jquery, form = layui.form, layer = layui.layer, table = layui.table,
            laytpl = layui.laytpl,laydate = layui.laydate, element = layui.element, util = layui.util;


        //更新数据表
        let hasInitTable = false;
        var tabIns;
        let updateable = function(formData){

            let complete = function () {
                $('#formQuerySearch').removeAttr('disable');
                window.resizeWindowHeight?window.resizeWindowHeight():'';
            };

            if(!hasInitTable){
                hasInitTable = true;
                //初始化表格
                tabIns = table.render({
                    title: (formData.yearMonth || '') + (formData.type || '') + '结算统计表',
                    elem: '#dataTable',
                    url: 'selectSettlement',
                    method: "POST",
                    loading: true,
                    width: '100%',
                    page: {
                        layout:['refresh', 'prev', 'page', 'next', 'count'],
                    },//开启分页
                    even: true, //隔行背景
                    size: 'sm', //大尺寸的表格
                    cellMinWidth: 80,
                    toolbar: true,
                    defaultToolbar: ['filter', 'print', 'exports', {
                        title: '导出所有',
                        layEvent: 'export_all',
                        icon: 'layui-icon-template-1' //图标类名
                    }],
                    limit: 15,
                    cols: [[
                        {field: 'YYNAME', title: '机构名字', width: 300},
                        {field: 'first', title: '一类', sort: true, width: 100},
                        {field: 'second', title: '二类', sort: true,width: 100},
                        {field: 'special', title: '特殊', sort: true,width: 100},
                        {field: 'aid', title: '帮困', sort: true,width: 100},
                        {field: 'total', title: '合计', sort: true,width: 120}
                    ]],
                    where: formData,
                    request: {
                        pageName: 'page', //页码的参数名称，默认：page
                        limitName: 'size' //每页数据量的参数名，默认：limit
                    },
                    parseData: function(res){ //res 即为原始返回的数据
                        let count = res.data && res.data.count || 0;
                        if(count > 0){ this.where.count = count; } //记录最大记录数
                        // console.log(count);
                        // console.log('this', this);
                        return {
                            "code": res.code, //解析接口状态
                            "msg": res.msg, //解析提示文本
                            "count": count, //解析数据长度
                            "data": res.data && res.data.data//解析数据列表
                        };
                    },

                    done: function () {
                        complete();

                    }

                });
                // console.log(tabIns);

            }else{
                tabIns.config.where = {}; //清除请求参数
                tabIns = table.reload('dataTable', {
                    title: (formData.yearMonth || '') + (formData.type || '') + '结算统计表',
                    where: formData,
                    page: {
                        curr: 1 //重新从第 1 页开始
                    },
                    done: function () {
                        console.log('重载完成');
                        complete();
                    },
                    error: function (error, data) {
                        console.log('重载失败', error);
                        complete();
                    }
                }); //只重载数据
            }

        };

        //校验表单参数
        let checkFormData = function(data){
            //查询日期
            if( !data.yearMonth){return false;}

            //检查查询机构姓名
            if(data.YYNAME.length == 0){
                // field.YYNAME = null;
                delete data.YYNAME;
            }
            return true;
        };

        let download = function(){
            let formData = form.val("filter-form");
            if(!checkFormData(formData)){return;}
            formData.count = 1; //防止查询时重新计数

            let loadingIndex = layer.load(2, {time: 10*1000}); //加载动画

            layui.config({//配置并导入excel插件
                base: '/js/layui_exts/'
            }).use('excel', function() {
                let excel = layui.excel;
                $.ajax({
                    url: 'selectSettlement',
                    method:'post',
                    data:formData,
                    success: (res) =>{
                        if(res.code != 0){
                            layer.msg(res.msg, {icon: 2});
                            return;
                        }

                        let data = res.data.data;
                        let fields = (function () {
                            let cols = tabIns.config.cols[0]; //表格表头
                            let fields = {};
                            let title = {};
                            for(let i in cols){
                                fields[cols[i].title] = cols[i].field;
                                title[cols[i].title] = cols[i].title;
                            }
                            return {title : title, fields: fields};

                        })();
                        // console.log('data', data);
                        // console.log('fields', fields);
                        data = excel.filterExportData(data, fields.fields);
                        data.unshift(fields.title);
                        // console.log('data', data);
                        excel.exportExcel(data, ['结算统计', formData.type || '',formData.yearMonth, '.xlsx'].join('-'), 'xlsx');
                    },
                    error: ()=> {
                        layer.msg(res.status || '未知的错误', {icon: 2});
                    },
                    complete: ()=>{
                        layer.close(loadingIndex);
                    }
                });
            });
        };


        //表格头部工具栏事件
        table.on('toolbar(dataTable)', function(obj){
            console.log('obj', obj);
            // var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'export_all':
                    download();
                    break;
            };
        });



        //表单提交
        form.on('submit(formQuerySearch)', function(data){
            // console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
            // console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
            // console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
            let field = data.field;
            console.log('field', field);

            if(!checkFormData(field)){return;}

            //发送请求
            updateable(field);

            //禁用当前按钮
            $(data.elem).attr('disable', 'disable');
            return false;
        });

        let defaultFormData = {
            yearMonth: '2020-12',
            type: '机构'
        };
        form.val("filter-form", defaultFormData);

        //日期
        laydate.render({
            elem: '#queryDate',
            type: 'month',
            value: defaultFormData.yearMonth,
            format: 'yyyy-MM',
            isInitValue: true,
            min: '2018-1-1',
            max: Date.now(),
            theme: 'grid'
        });

        form.render();

        //初始渲染
        updateable(defaultFormData);

    })
});